﻿

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using SharpDX;
using SharpDX.XAPO;
using SynergyLib.SMath;


namespace XAudio2Controls
{
    [StructLayout(LayoutKind.Sequential)]
    public struct TremoloParams
    {
        internal float ModulationFrequency { get; set; }
    }

    /// <summary>
    /// A simple Ring Modulator Effect
    /// </summary>
    public class TremoloEffect : AudioProcessorBase<TremoloParams>
    {
        public TremoloEffect()
        {
            RegistrationProperties = new RegistrationProperties()
            {
                Clsid = Utilities.GetGuidFromType(typeof(TremoloEffect)),
                CopyrightInfo = "Copyright",
                FriendlyName = "Tremolo",
                MaxInputBufferCount = 10000,
                MaxOutputBufferCount = 10000,
                MinInputBufferCount = 1000,
                MinOutputBufferCount = 1000,
                Flags = PropertyFlags.Default
            };
        }
        
        public override void Process(BufferParameters[] inputProcessParameters, BufferParameters[] outputProcessParameters, bool isEnabled)
        {
            int frameCount = inputProcessParameters[0].ValidFrameCount;

            DataStream input = new DataStream(inputProcessParameters[0].Buffer, frameCount * InputFormatLocked.BlockAlign, true, true);
            DataStream output = new DataStream(inputProcessParameters[0].Buffer, frameCount * InputFormatLocked.BlockAlign, true, true);
            
            for (int i = 0; i < frameCount; i++, Counter++)
            {
                float left = input.Read<float>();
                float right = input.Read<float>();
               
                double tremolo =  1 + Math.Sin(Trig.TwoPI * Counter * (Parameters.ModulationFrequency) / InputFormatLocked.SampleRate);

                output.Write((float)(tremolo * left)); 
                output.Write((float)(tremolo * right));
            }           
        }       
    }
}